﻿using Microsoft.AspNetCore.Mvc;
using SkyApm.Tracing;
using System.Collections.Generic;
using System;
using System.Threading;
using SkyApm.Tracing.Segments;
using WebApmDemo1.Models;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace WebApmDemo1.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SkywalkingController : ControllerBase
    {
        private readonly IEntrySegmentContextAccessor segContext;

        public SkywalkingController(IEntrySegmentContextAccessor segContext)
        {
            this.segContext = segContext;
        }

        [HttpGet("test")]
        public string TestSkywalking()
        {
            return "TestSkywalking";
        }

        /// <summary>
        /// 获取链接追踪ID
        /// </summary>
        /// <returns></returns>
        [HttpGet("traceId")]
        public string GetSkywalkingTraceId()
        {
            return segContext.Context.TraceId;
        }

        /// <summary>
        /// 自定义链路调用中的日志信息
        /// </summary>
        /// <returns></returns>
        [HttpGet, HttpPost, Route("SkywalkingTest1")]
        public IActionResult SkywalkingTest1()
        {
            //获取全局的skywalking的TracId
            var TraceId = segContext.Context.TraceId;
            Console.WriteLine($"TraceId={TraceId}");
            segContext.Context.Span.AddLog(LogEvent.Message($"SkywalkingTest1---Worker running at: {DateTime.Now}"));

            Thread.Sleep(1000);

            segContext.Context.Span.AddLog(LogEvent.Message($"SkywalkingTest1---Worker running at--end: {DateTime.Now}"));

            return Ok($"Ok,SkywalkingTest1-TraceId={TraceId} ");
        }

        /// <summary>
        /// 告警API
        /// </summary>
        /// <param name="msgs"></param>
        /// <returns></returns>
        [HttpPost, Route("SkyAlarmMsg"), SkyWalkingFilter]
        public async Task<string> SkyAlarmMsg(List<AlarmMsg> msgs)
        //public async Task<string> SkyAlarmMsg(object msgs)
        {
            //string msgStr = JsonConvert.SerializeObject(msgs);
            //var alarmMsg = JsonConvert.DeserializeObject<List<AlarmMsg>>(msgStr);
            string msg = "触发告警：";
            foreach (var alarm in msgs)
            {
                msg += alarm.alarmMessage + "\r\n";
            }
            Console.WriteLine(msg);
            await SendMail(msg);
            return $"Ok:{msg}";
        }

        /// <summary>
        /// 告警API
        /// </summary>
        /// <param name="msgs"></param>
        /// <returns></returns>
        [HttpGet("ex")]
        public void AlarmMsg1()
        {
            int a = 1;
            int b = 0;
            int c = a / b;
        }

        private async Task SendMail(string msg)
        {
            await Task.Run(() => segContext.Context.Span.AddLog(LogEvent.Message($"SkywalkingTest1---触发告警===>: {msg}")));
            Console.WriteLine("触发告警===> 发送邮件");
        }
    }

}
